package com.bmp.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import com.bmp.dao.GroupsDao;
import com.bmp.model.Groups;
import com.bmp.util.HibernateUtil;
@Component("groupsDao")
public class GroupsDaoImpl implements GroupsDao {
	private HibernateTemplate hibernateTemplate;
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void deleteGroupsById(int id) {
		Groups g = this.getGroupsById(id);
		this.hibernateTemplate.delete(g);
	}

	public Groups getGroupsById(int id) {
		return (Groups)this.hibernateTemplate.get(Groups.class, id);
		//List<Groups> groups = hibernateTemplate.find("from Groups g where g.id='"+id+"'");
		//if(groups.isEmpty())  return null;
		//else
		//return groups.get(0);
	}

	public void insertGroups(Groups g) {
		this.hibernateTemplate.save(g);
	}

	public void updateGroups(Groups g) {
		this.hibernateTemplate.update(g);
	}
	//获取每一页的信息
	@SuppressWarnings("unchecked")
	public List<Groups> getGroups(int page, int rows) {
		List<Groups> list = null;
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		String sql = "from Groups g";
		list = session.createQuery(sql).setFirstResult((page-1)*rows).setMaxResults(rows).list();
		session.getTransaction().commit();
		System.out.println("getGroups");
		return list;
	}
	//获取总记录数
	public int getTotalPages() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		String sql = "select count(*) from Groups g";
		long count = (Long)session.createQuery(sql).uniqueResult();
		session.getTransaction().commit();
		System.out.println(count);
		return (int)count;
	}
}
